package org.example.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import org.example.domain.CarPlan;
import org.example.service.CarPlanService;

import java.util.List;

/**
 * @author : Guosir
 * @date : 2024-06-30 13:23
 * @description :
 **/
public class CarPlanListener implements ReadListener<CarPlan> {

    private static  final int BACH_COUNT = 3;


    private List<CarPlan> cacheDataList = ListUtils.newArrayListWithExpectedSize(BACH_COUNT);


    private CarPlanService carPlanService;

    public CarPlanListener(CarPlanService carPlanService) {
        this.carPlanService=carPlanService;
    }

    @Override
    public void invoke(CarPlan carPlan, AnalysisContext analysisContext) {

        System.out.println("解析出来的数据："+carPlan);

        cacheDataList.add(carPlan);

        if(cacheDataList.size()>=BACH_COUNT){
            //保存到数据库
            System.out.println("list:"+cacheDataList);

            carPlanService.saveBatch(cacheDataList);

            //重新赋值
            cacheDataList = ListUtils.newArrayListWithExpectedSize(BACH_COUNT);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        System.out.println("解析完成");

        if(cacheDataList.size()>0){
            //最后一次添加
            carPlanService.saveBatch(cacheDataList);
            System.out.println("list:"+cacheDataList);
        }
    }
}
